//
//  DrawView.m
//  08-画板
//
//  Created by J on 16/3/24.
//  Copyright © 2016年 J. All rights reserved.
//

#import "DrawView.h"
#import "DrawPath.h"

@interface DrawView()
@property(nonatomic,strong)DrawPath* path ;//自定义贝塞尔曲线 目的是需要添加一个颜色属性 自带的没有这个属性
@property(nonatomic,strong)NSMutableArray* paths ;

@end
@implementation DrawView

- (void)setImage:(UIImage *)image{
    [self.paths addObject:image];
    [self setNeedsDisplay];
}


//只要调用这个方法 之前的内容就会被清空
- (void)drawRect:(CGRect)rect{
    for (DrawPath* path in self.paths) {
        //判断路径数组里的内容是不是图片
        if ([path isKindOfClass:[UIImage class]]) {//当前类或者子类对象
            UIImage* image = (UIImage*)path;
            [image drawInRect:rect];//直接把图片画出来
        }else{//如果不是照片 直接画线
            
            [path.pathColor set];//设置线颜色
            [path stroke];//在图形上下文中画线
        }
        
    }
    
    
}






- (UIBezierPath *)path{
    
    if (!_path) {
        //创建路径
        DrawPath* path = [DrawPath bezierPath];
        path.pathColor = [UIColor blackColor];//初始化线的颜色
        _path = path;
    }
    return _path;
}


- (NSMutableArray *)paths{
    if (!_paths) {
        _paths  = [NSMutableArray array];
    }
    return _paths;
}




#pragma mark 初始化视图
//这两个方法都重写 是为了 保证不论哪种方式创建都能初始化相同的内容
//此处添加手势
- (void)awakeFromNib{
    [self setUp];
}


//通过代码初始化的时候调用
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self setUp];
    }
    return self;
}




#pragma mark 画图pan手势

//初始化设置
- (void)setUp{
    //添加pan手势
    UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [self addGestureRecognizer:pan];
    self.lineWidth = 1.0;//初始化的时候设置线宽

    
}




- (void)pan:(UIPanGestureRecognizer*)pan{
//    NSLog(@"pan");
    //获取手指触摸点
    CGPoint currentPoint = [pan locationInView:self];
    
    if (pan.state == UIGestureRecognizerStateBegan) {//开始点击屏幕
        //创建路径
        _path = [DrawPath bezierPath];
        _path.lineWidth = self.lineWidth;//线宽
        _path.pathColor = _pathColor;//设置线的颜色

        //保存当前路径到数组
        [self.paths addObject:_path];
        //设置路径起点
        [self.path moveToPoint:currentPoint];
    }
    
    //手指一直在拖动

     [_path addLineToPoint:currentPoint];
    
    //重绘
    [self setNeedsDisplay];//调用 drawRect
    
}




//清屏

- (void)clear{
    
    [_paths removeAllObjects];
    [self setNeedsDisplay];//drawrect

    
}
//撤销
- (void)remove{
    [_paths removeLastObject];
    [self setNeedsDisplay];//drawrect
 
}



@end
